package com.cd2cd.code_template.curd.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cd2cd.code_template.code_template.domain.SysAuth;
import com.cd2cd.code_template.code_template.mapper.SysAuthMapper;
import com.cd2cd.code_template.configuration.constants.AuthTypeEnum;
import com.cd2cd.code_template.configuration.constants.DBConstants;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Component
public class CURDConfig {

    public static final String CURD_REQUEST_URL = "curd";

    private static final char UNDERLINE = '_';
    private static Logger log = LoggerFactory.getLogger(CURDConfig.class);

    private static final Map<String, Map<String, JSONObject>> CURD_CACHE = new HashMap<>();


    @Resource
    private SysAuthMapper sysAuthMapper;

    @PostConstruct
    private void init() throws Exception {
        // 读取配置文件 进行数据初始化
        InputStream curdStream = this.getClass().getResourceAsStream("/CURDConfig.json");
        String s = IOUtils.toString(curdStream, "utf-8");

        JSONArray arrData = JSONArray.parseArray(s);

        // 初始化权限
        authControl(arrData);

        for (Object arrDatum : arrData) {
            JSONObject dataObj = JSONObject.parseObject(arrDatum.toString());
            String tableName = dataObj.getString("tableName");

            Map<String, JSONObject> map = new HashMap<>();
            map.put("l", dataObj.getJSONObject("l"));
            map.put("c", dataObj.getJSONObject("c"));
            map.put("u", dataObj.getJSONObject("u"));
            map.put("r", dataObj.getJSONObject("r"));
            map.put("d", dataObj.getJSONObject("d"));

            CURD_CACHE.put(tableName, map);
        }
    }

    // 检测是否启用
    public static Boolean testEnable(String tableName, String key) {

        // 检测表是否存在
        Map<String, JSONObject> map = CURD_CACHE.get(tableName);
        if (null == map){
            return false;
        }

        // 检测curd
        JSONObject obj = map.get(key);
        return obj.getBoolean("use");
    }

    // 获取 c,u,r,d,l  数据
    public static JSONObject getData(String tableName, String key) {

        Map<String, JSONObject> map = CURD_CACHE.get(tableName);
        if (null == map){
            return null;
        }

        return map.get(key);
    }

    // list 返回select查询条件
    public static JSONObject selectCondition(String tableName) {

        Map<String, JSONObject> map = CURD_CACHE.get(tableName);

        if (null == map){
            return null;
        }

        JSONObject lObj = map.get("l");
        return lObj.getJSONObject("select");
    }


    // 获取不返回的字段
    public static JSONArray getNotRetField(String tableName,String key){
        Map<String, JSONObject> map = CURD_CACHE.get(tableName);

        if (null == map){
            return null;
        }

        JSONObject lObj = map.get(key);

        JSONArray array = new JSONArray();

        JSONArray notReturn = lObj.getJSONArray("notReturn");
        for (Object o : notReturn) {
            array.add(underlineToCamel(o.toString(),false));
        }
        return array;
    }


    // 获取rule
    public static JSONObject getRuleDate(String tableName,String key) {
        Map<String, JSONObject> map = CURD_CACHE.get(tableName);

        if (null == map){
            return null;
        }
        JSONObject lObj = map.get(key);
        return lObj.getJSONObject("rule");
    }


    //获取rule 参数
    public static JSONArray getRuleParams(String value) {
        JSONArray array = new JSONArray();

        int startIndex = value.indexOf("(");
        int endIndex = value.indexOf(")");

        String substring = value.substring(startIndex + 1, endIndex);

        if (substring.contains(",")) {
            String[] split = substring.split(",");
            array.addAll(Arrays.asList(split));
        }else {
            array.add(substring);
        }

        return array;
    }


    // 初始化权限
    private void authControl(JSONArray arrData) {

        for (Object arrDatum : arrData) {
            JSONObject dataObj = JSONObject.parseObject(arrDatum.toString());
            String tableName = dataObj.getString("tableName");
            String comment = dataObj.getString("comment");
            String routePath = dataObj.getString("routePath");

            SysAuth sysAuthClass = new SysAuth();
            sysAuthClass.setGuid(tableName);
            sysAuthClass.setAuthType(DBConstants.AuthType.MENU);
            sysAuthClass.setName(comment);
            sysAuthClass.setRoutePath(routePath);
            sysAuthClass.setType(AuthTypeEnum.Backend.name());
            sysAuthClass.setAuth(DBConstants.BoolStr.YES);

            sysAuthMapper.insertOrUpdate(sysAuthClass);

            JSONObject l = dataObj.getJSONObject("l");
            JSONObject c = dataObj.getJSONObject("c");
            JSONObject u = dataObj.getJSONObject("u");
            JSONObject r = dataObj.getJSONObject("r");
            JSONObject d = dataObj.getJSONObject("d");


            if (l.getBoolean("use")) {
                insertOrUpdateMethod("entityPage","",CURD_REQUEST_URL + "/" + tableName + "/page",sysAuthClass.getId());
            }

            String url = CURD_REQUEST_URL + "/" + tableName + "/Info";

            if (c.getBoolean("use")) {
                insertOrUpdateMethod("entityAdd","POST",url,sysAuthClass.getId());
            }


            if (u.getBoolean("use")) {
                insertOrUpdateMethod("entityUpdate","PUT",url,sysAuthClass.getId());
            }

            if (r.getBoolean("use")) {
                insertOrUpdateMethod("entityInfo","GET",url,sysAuthClass.getId());
            }

            if (d.getBoolean("use")) {
                insertOrUpdateMethod("entityDel","DELETE",url,sysAuthClass.getId());
            }

        }


    }

    // 方法 权限更新
    private void insertOrUpdateMethod(String methodName,String mode,String url,Integer superId) {
        SysAuth sysAuthMethod = new SysAuth();

        sysAuthMethod.setType(AuthTypeEnum.Backend.name());
        sysAuthMethod.setAuth(DBConstants.BoolStr.YES);
        sysAuthMethod.setName(methodName);
        sysAuthMethod.setAuthType(DBConstants.AuthType.AUTH);
        sysAuthMethod.setGuid(mode.toLowerCase() + "_" + url.replaceAll("/","_"));
        sysAuthMethod.setUrl(url);
        sysAuthMethod.setMode(mode);
        sysAuthMethod.setPid(superId);

        sysAuthMapper.insertOrUpdate(sysAuthMethod);
    }



    // 下划线格式字符串转换为驼峰格式字符串  firstCapitalize: 首字母是否大写
    public static String underlineToCamel(String param,Boolean firstCapitalize) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);

            if (c == UNDERLINE && i != 0) {
                if (++i < len) {
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }
            } else {
                if (i == 0 && firstCapitalize){
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }else {
                    sb.append(c);
                }

            }
        }
        return sb.toString();
    }

    public enum ruleVerify {
        NotNull,Mobile,Email,IdCard,Max,Min,Range
    }


    public static void main(String[] args) {
        String aaaa_sss_ddd_cccc = underlineToCamel("aaaa_sss_ddd_cccc",true);

        System.out.println(aaaa_sss_ddd_cccc);

    }


}
